//获取登录注册的按钮
var denglu = document.lastElementChild.getElementsByClassName("dis-no")[0];
var diszhuce = document.getElementsByClassName("diszhuce")[0];
var zheceyemian = document.getElementById('dis-zhu');
var dengluyemian = document.getElementById('dis-denglu');
// console.log(diszhuce);
//绑定切换登录注册按钮的事件
denglu.onclick = function () {
    // console.log(zheceyemian.style.display);
    if (zheceyemian.style.display == '') {
        zheceyemian.style.display = 'none';
        dengluyemian.style.display = '';
    }
}
diszhuce.onclick = function () {
    if (dengluyemian.style.display == "") {
        dengluyemian.style.display = 'none';
        zheceyemian.style.display = '';
    }
}

//验证码
// 定义获取任意区间[min,max)随机函数
var gr = function (min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}
//随机产生颜色
var rc = function (min, max) {
    var r = gr(min, max);
    var g = gr(min, max);
    var b = gr(min, max);
    // return "rgb("+r+","+g+","+b+")";
    return `rgb(${r},${g},${b})`;
}
//获取4位验证码文本
var getCode = function () {
    var code = "";
    var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var arr = str.split("");//将字符串分隔为由其每个字符组成的数组
    for (var i = 0, index = 0; i < 4; i++) {
        index = Math.floor(Math.random() * arr.length);//获取0-61的随机数作为索引
        code += arr[index];//获取索引对应的字符
    }
    return code;
}
//定义生成图形验证码
var draw = function () {
    //获得canvas对象
    var canvas = document.getElementById("canvas1");
    //获得2d上下文对象，该对象提供了一系列属性和方法来绘制图形           
    var cxt = canvas.getContext("2d");
    var w = canvas.clientWidth;//画布宽度,图形宽度及坐标x轴不能超过w
    var h = canvas.clientHeight;//画布高度
    // console.log(w, h);
    //从左上角开始绘制一个与画布一般大小的矩形并填充随机颜色(形成背景色)
    cxt.fillStyle = rc(180, 230);
    cxt.fillRect(0, 0, w, h);
    //获取随机生成的验证码
    var yzm = getCode();
    // console.log(yzm);
    //绘制验证码文本
    cxt.font = "italic bold 30px SimHei";
    cxt.strokeStyle = rc(0, 255);
    cxt.strokeText(yzm, 25, 35);
    //绘制4条干扰线
    for (var i = 0; i < 4; i++) {
        cxt.beginPath();
        cxt.lineWidth = 1;//设置线条宽度，px
        cxt.strokeStyle = rc(0, 255);//设置笔触的颜色
        cxt.moveTo(gr(0, w), gr(0, h));
        cxt.lineTo(gr(0, w), gr(0, h));
        cxt.closePath();
        cxt.stroke();
    }
    //绘制20个干扰点
    for (var i = 0; i < 20; i++) {
        cxt.fillStyle = rc(0, 256);
        cxt.beginPath();
        cxt.arc(gr(0, w), gr(0, h), 1, 0, 2 * Math.PI);//实心圆点
        cxt.fill();
    }
    return yzm;
}
var draw1 = function () {
    //获得canvas对象
    var canvas = document.getElementById("canvas2");
    //获得2d上下文对象，该对象提供了一系列属性和方法来绘制图形           
    var cxt = canvas.getContext("2d");
    var w = canvas.clientWidth;//画布宽度,图形宽度及坐标x轴不能超过w
    var h = canvas.clientHeight;//画布高度
    // console.log(w, h);
    //从左上角开始绘制一个与画布一般大小的矩形并填充随机颜色(形成背景色)
    cxt.fillStyle = rc(180, 230);
    cxt.fillRect(0, 0, w, h);
    //获取随机生成的验证码
    var yzm = getCode();
    // console.log(yzm);
    //绘制验证码文本
    cxt.font = "italic bold 30px SimHei";
    cxt.strokeStyle = rc(0, 255);
    cxt.strokeText(yzm, 25, 35);
    //绘制4条干扰线
    for (var i = 0; i < 4; i++) {
        cxt.beginPath();
        cxt.lineWidth = 1;//设置线条宽度，px
        cxt.strokeStyle = rc(0, 255);//设置笔触的颜色
        cxt.moveTo(gr(0, w), gr(0, h));
        cxt.lineTo(gr(0, w), gr(0, h));
        cxt.closePath();
        cxt.stroke();
    }
    //绘制20个干扰点
    for (var i = 0; i < 20; i++) {
        cxt.fillStyle = rc(0, 256);
        cxt.beginPath();
        cxt.arc(gr(0, w), gr(0, h), 1, 0, 2 * Math.PI);//实心圆点
        cxt.fill();
    }
    return yzm;
}
//页面加载时生成验证码,将生成的验证码文本保存到_yzm中
var _yzm = draw().toLowerCase();
var _yzm1 = draw1().toLowerCase();
//点击画布也重新生成验证码
document.getElementById("canvas1").onclick = () => {
    _yzm = draw().toLowerCase();
}
document.getElementById("canvas2").onclick = () => {
    _yzm1 = draw1().toLowerCase();
}
//验证输入的验证码是否正确
// 登录
var checkCode = function () {
    //获取输入的验证码
    var iyzm = document.getElementById("input-yzm");
    var shuRu = iyzm.value.toLowerCase();//统一转小写作比较
    // console.log(shuRu, _yzm);
    if (shuRu == _yzm) {
        loginYmsg.innerHTML = "";
    } else {
        loginYmsg.innerHTML = "验证码输入错误,请重新输入"
        iyzm.value = "";//清空
        //验证码输入框聚焦
        iyzm.focus();
    }
}
// 注册
var checkCode2 = function () {
    //获取输入的验证码
    var iyzm = document.getElementById("input-yzm1");
    var shuRu = iyzm.value.toLowerCase();
    if (shuRu == _yzm1) {
        regYmsg.innerHTML = "";
    } else {
        regYmsg.innerHTML = "验证码输入错误,请重新输入"
        iyzm.value = "";//清空
        //验证码输入框聚焦
        iyzm.focus();
    }
}


//用户名检验是否为空
function login_User_blur() {
    let _loginUser = loginUser.value;

    if (!_loginUser) {
        loginUmsg.innerHTML = "手机号码不能为空！";
    } else {
        loginUmsg.innerHTML = "";
    }
}
//密码检验
function login_Pwd_blur() {
    let _loginPwd = loginPwd.value;

    if (!_loginPwd) {
        loginPmsg.innerHTML = "密码不能为空！";
    } else {
        loginPmsg.innerHTML = "";
    }
}
//ajax登录
function login() {
    login_User_blur();
    login_Pwd_blur();
    checkCode();

    if (loginUmsg.innerHTML === '' && loginPmsg.innerHTML === '' && loginYmsg.innerHTML === '') {
        let login_phone = loginUser.value;
        let login_pwd = loginPwd.value;

        ajax({
            url: '/user/login',
            type: 'get',
            data: `${login_phone}&${login_pwd}`,
            success: function (data) {
                data = JSON.parse(data)[0];
                // console.log(data);
                if (data != null) {
                    //当登录手机和密码正确时，将uid和uname保存起来
                    localStorage.setItem('uid',data.uid);
                    localStorage.setItem('uname',data.uname);
                    alert('登录成功');
                    location.replace('/');
                } else {
                    loginUmsg.innerHTML = "用户名或密码错误";
                }
            },
            error: function (e) {
                console.log(e);
            }
        });
    }
}

//判断用户名是否重复
function reg_User_blur() {
    let _regUser = regUser.value;

    if (!_regUser) {
        regUmsg.innerHTML = '手机号码不能为空！';
    } else if (!(/^1[3-9]\d{9}$/.test(_regUser))) {
        regUmsg.innerHTML = '手机号不正确';
    } else {

        ajax({
            url: '/user/getUname',
            type: 'get',
            data: _regUser,
            success: function (data) {
                if (data == 1) {
                    return regUmsg.innerHTML = '手机号码已被注册';
                }
                regUmsg.innerHTML = '';
            },
            error: function (e) {
                console.log(e);
            }
        });
    }
}
//判断密码
function reg_Pwd_blur() {
    let _regPwd = regPwd.value;

    if (!_regPwd) {
        regPmsg.innerHTML = '密码不能为空！';
    } else if (!(/^[A-Za-z0-9]{6,10}$/.test(_regPwd))) {
        regPmsg.innerHTML = '密码为字母或数字，6到10位';
    } else {
        regPmsg.innerHTML = '';
    }
}
//注册用户
function reg() {
    reg_User_blur();
    reg_Pwd_blur();
    checkCode2();

    let msg = '';
    if (regUmsg.innerHTML === '' && regPmsg.innerHTML === '' && regYmsg.innerHTML === "") {
        //判断选择框是否选中
        if (agree.checked) {
            let reg_User = regUser.value;
            let reg_Pwd = regPwd.value;

            ajax({
                url: '/user/reg',
                type: 'post',
                data: `uname=${reg_User}&upwd=${reg_Pwd}&phone=${reg_User}`,
                success: function (data) {
                    if (data == 1) {
                        alert('注册成功');
                        //注册成功时将注册页隐藏，登录页显示
                        zheceyemian.style.display = 'none';
                        dengluyemian.style.display = '';
                    } else {
                        alert('注册失败');
                    }
                },
                error: function (e) {
                    console.log(e);
                }
            });
        } else {
            msg = '须同意《用户服务协议》';
        }
    }
    agree_msg.innerHTML = msg;
}